<template>
  <div style="padding: 10px;">
    <!--<Particles></Particles>-->
    <!--功能区域-->
    <div style="margin: 10px 0">
      <el-button type="success" round @click="add" v-if="user.role===1">新增</el-button>
      <el-button type="primary" round>导入</el-button>
      <el-button type="success" round>导出</el-button>
    </div>

    <!--搜索-->
    <div style="margin: 10px; text-align: center;margin-left: -120px;border-radius: 20px">
      <el-input @keyup.enter.native="load" v-model="search" placeholder="请输入关键字"
                style="border-radius: 20px;width: 20%;" clearable=""></el-input>
      <el-button type="primary" style="margin-left: 7px" @click="load">查询</el-button>
    </div>

    <el-table
      :data="tableData"
      border
      stripe=""
      size="small"
      style="width: 100%">
      <el-table-column
        prop="id"
        sortable=""
        label="ID">
      </el-table-column>
      <el-table-column
        prop="username"
        label="用户名">
      </el-table-column>
      <el-table-column
        prop="nick"
        label="昵称">
      </el-table-column>
      <el-table-column
        prop="age"
        label="年龄">
      </el-table-column>
      <el-table-column
        prop="sex"
        label="性别">
      </el-table-column>
      <el-table-column
        prop="address"
        label="住址">
      </el-table-column>
      <el-table-column label="角色">

        <template slot-scope="scope">
          <!--<span v-if="scope.row.role===1">管理员</span>-->
          <!--<span v-if="scope.row.role===2">普通用户</span>-->
          <el-tag :type="scope.row.role === 1?'success':''">
            {{scope.row.role === 1? '管理员': '普通用户'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="头像">
        <template slot-scope="scope">
          <el-image
            style="width: 45%; height: 45%;"

            :src="scope.row.avatar"
            :preview-src-list="[scope.row.avatar]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        width="170px"
        fixed="right"
        label="操作">
        <template slot-scope="scope">
          <el-button title="拥有的图书列表" type="success" plain @click="showBooks(scope.row.bookList)">图书
          </el-button>
          <!--编辑-->
          <el-button type="primary" title="编辑" @click="handleEdit(scope.row)" v-if="user.role===1"
                     icon="el-icon-edit" circle></el-button>

          <!--删除-->
          <el-button @click="handleDelete(scope.row.id)" title="删除"
                     slot="reference" type="danger" icon="el-icon-delete" circle
                     style="margin-left: 10px" v-if="user.role===1"></el-button>


        </template>
      </el-table-column>
    </el-table>


    <!--分页-->
    <div style="margin: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage4"
        :page-sizes="[5,10,20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <el-dialog title="用户拥有的图书列表" :visible.sync="bookVis" width="30%">
        <el-table :data="bookList" stripe border>
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="author" label="作者"></el-table-column>
          <el-table-column prop="price" label="价格/元"></el-table-column>
        </el-table>
      </el-dialog>

      <!--新增-->
      <el-dialog

        title="新增"
        :visible.sync="dialogVisible"
        width="30%">
        <el-form :model="form" label-width="120px">
          <el-form-item label="用户名">
            <el-input v-model="form.username" style="width: 80%" disabled=""></el-input>
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="form.nick" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="form.age" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="性别">
            <el-radio v-model="form.sex" label="男">男</el-radio>
            <el-radio v-model="form.sex" label="女">女</el-radio>
            <el-radio v-model="form.sex" label="未知">未知</el-radio>

          </el-form-item>
          <el-form-item label="地址">
            <el-input type="textarea" v-model="form.address" style="width: 80%"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-tag :type="form.role === 1?'success':''">
              {{form.role === 1? '管理员': '普通用户'}}
            </el-tag>
            <el-select v-model="form.newRole" placeholder="请选择">

              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              ref="upload"
              action="http://127.0.0.1/files/upload"
              :on-success="filesUploadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>

            </el-upload>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
  </span>
      </el-dialog>
    </div>


  </div>
</template>

<script>
  // @ is an alias to /src

  import request from '@/utils/request'


  export default {
    name: 'User',

    data() {
      return {
        bookList: [],
        bookVis: false,
        options: [{
          value: '1',
          label: '管理员'
        }, {
          value: '2',
          label: '普通用户'
        }],
        form: {},
        user: {},
        //新增
        dialogVisible: false,
        search: '',
        //当前页
        currentPage4: 1,
        pageSize:10,
        total: 0,
        roleName: "",
        tableData: []
      }


    },
    created() {
      let userStr = sessionStorage.getItem("user") || "{}"
      this.user = JSON.parse(userStr)
      this.load()
      //请求服务端，确认当前登录用户的 合法信息
      // request.get("/user/" + this.user.id).then(res => {
      //     if (res.code === 20000) {
      //         this.user = res.data
      //     }
      // })
    },
    methods: {
      showBooks(books) {
        this.bookVis = true
        this.bookList = books
        request.get('/users/', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search
          }

        }).then(res => {
          console.log(res)
          this.tableData = res.data.records
          this.total = res.data.total


        })



      },
      filesUploadSuccess(res) {
        console.log(res)
        this.form.avatar = res.data;
      },
      //查询
      load() {
        request.get('/users/query', {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            search: this.search
          }

        }).then(res => {
          console.log(res)
          this.tableData = res.data.records
          this.total = res.data.total


        })

      },

      //新增
      add() {
        this.dialogVisible = true
        this.form = {} //清空输入的表单
        this.load()
        this.$nextTick(() => {
          this.$refs['upload'].clearFiles() //清除历史文件列表
        })

      },
      //保存到后台
      save() {
        if (this.form.id) {
//    更新
          if (this.form['newRole']) {
            this.form.role = parseInt(this.form['newRole'])
          }
          request.put("/users", this.form).then(res => {
            if (res.code ===20000) {
              this.$message({
                message: '更新成功',
                type: 'success',

              });
              this.load()
            } else {
              this.$message({

                message: res.msg,
                type: 'error',

              })
            }

          })
          this.dialogVisible = false
          this.load()
        } else {
//    新增
          request.post("/users", this.form).then(res => {
            console.log(res)
            this.dialogVisible = false
            if (res.code ===20000) {


              this.$message({
                message: '添加成功',
                type: 'success',

              });
              this.load()
            }

            else {
              this.$message({

                message: res.msg,
                type: 'error',

              })
            }
          })
        }


      },
      //编辑
      handleEdit(row) {
        // role:{
        //      id:1,
        //      displayName: '管理员'
        // }
        this.form = JSON.parse(JSON.stringify(row))
        this.dialogVisible = true
        // this.roleName=(row.role===1 ?"管理员":"普通员工")
        this.$nextTick(() => {
          this.$refs['upload'].clearFiles() //清除历史文件列表
        })
      },
      handleDelete(id) {

        this.$confirm('你确定要删除,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          request.delete("/users/" + id).then(res => {

            this.$message({type: 'success', message: '删除成功!'})
            this.load()
          })
        }).catch(() => {
          this.$message({type: 'success', message: '已取消删除'})
        })


      },
      //页码 每页的个数
      handleSizeChange(pageSize) {
        this.pageSize = pageSize
        this.load()
      },
      //改变当前页
      handleCurrentChange(pageNum) {
        this.currentPage = pageNum
        this.load()
      },

    }
  }
</script>

<style scoped>

  el-input {
    border-radius: 20px
  }
</style>
